package com.xin.data.simbapesa.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.gson.JsonObject;
import com.xin.data.simbapesa.PathMaping;
import com.xin.data.simbapesa.R;
import com.xin.data.simbapesa.adapter.QuestionTypeAdapter;
import com.xin.data.simbapesa.adapter.UploadImgAdapter;
import com.xin.data.simbapesa.api.PU;
import com.xin.data.simbapesa.api.RxHttp;
import com.xin.data.simbapesa.api.U;
import com.xin.data.simbapesa.base.BaseActivity;
import com.xin.data.simbapesa.base.BaseDialog;
import com.xin.data.simbapesa.base.BaseParams;
import com.xin.data.simbapesa.databinding.SimbaFeedbackActivityBinding;
import com.xin.data.simbapesa.dialog.PhotoDialog;
import com.xin.data.simbapesa.utils.AESCryptUtilJar;
import com.xin.data.simbapesa.utils.FileUtils;
import com.xin.data.simbapesa.utils.ImgUitls;
import com.xin.data.simbapesa.utils.JsonParse;
import com.xin.data.simbapesa.utils.LogUtil;
import com.xin.data.simbapesa.utils.ResUtils;
import com.xin.data.simbapesa.utils.SpUtils;
import com.xin.data.simbapesa.utils.Tools;
import com.xin.data.simbapesa.utils.ViewUtils;
import com.xin.data.simbapesa.view.SimbaSpaceItemDecoration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class SimbaFeedbackActivity extends BaseActivity<SimbaFeedbackActivityBinding> {


    UploadImgAdapter imgAdapter;
    List<String> list2;

    QuestionTypeAdapter typeAdapter;

    List<String> list1;


    int score;

    ActivityResultLauncher<PickVisualMediaRequest> pickMedia;

    PhotoDialog photoDialog;

    private final int TIME_WHAT = 1;


    @Override
    protected SimbaFeedbackActivityBinding initViewBinding(LayoutInflater inflater) {
        return SimbaFeedbackActivityBinding.inflate(inflater);
    }

    @Override
    protected void initView() {

        binding.tvEmailTitle.setText(Html.fromHtml(ResUtils.s(R.string.feedback_title4)));


        score = getIntent().getIntExtra("score", -1);

        binding.tvInput.setType(PU.P212);
        binding.tvEmail.setType(PU.P213);


        binding.tvBk.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            finish();
        });
        binding.tvCs.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            startActivity(new Intent(getActivity(),SimbaCustomerServiceActivity.class));
        });
        binding.tvBtn.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            PU.userBuriedPoint(PU.P112, "");
            submit();
        });

        binding.tvRoot1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Tools.hideSoftInputFromWindow(getActivity(), binding.tvRoot);
            }
        });


        list1 = new ArrayList<>();
        list1.add(ResUtils.s(R.string.question_type_title1));
        list1.add(ResUtils.s(R.string.question_type_title2));
        list1.add(ResUtils.s(R.string.question_type_title3));
        list1.add(ResUtils.s(R.string.question_type_title4));


        GridLayoutManager layoutManager1 = getGridLayoutManager();
        binding.recyclerView1.setLayoutManager(layoutManager1);
        int d1 = ResUtils.d(R.dimen.dp_4);
        binding.recyclerView1.addItemDecoration(new SimbaSpaceItemDecoration(d1, d1, getActivity()));
        typeAdapter = new QuestionTypeAdapter(list1);
        binding.recyclerView1.setAdapter(typeAdapter);

        list2 = new ArrayList<>();
        GridLayoutManager layoutManager2 = new GridLayoutManager(getApplicationContext(), 3);
        layoutManager2.setOrientation(LinearLayoutManager.VERTICAL);
        binding.recyclerView2.setLayoutManager(layoutManager2);
        int d2 = ResUtils.d(R.dimen.dp_8);
        binding.recyclerView2.addItemDecoration(new SimbaSpaceItemDecoration(d2, d2, getActivity()));
        list2.add("");
        imgAdapter = new UploadImgAdapter(list2);
        imgAdapter.setOnBtnItemClickListener(position -> {
            if (TextUtils.isEmpty(list2.get(position))) {
                PU.userBuriedPoint(PU.P109, "");
                showPhotoChooseDialog();
            } else {
                PU.userBuriedPoint(PU.P108, "");
                deleteImg(position);
            }
            Tools.hideSoftInputFromWindow(getActivity(), binding.tvRoot);
        });
        binding.recyclerView2.setAdapter(imgAdapter);

    }

    @Override
    protected void initData() {
        UP_TYPE1 = PU.P106;
        UP_TYPE2 = PU.P107;
        pickMedia = registerForActivityResult(new ActivityResultContracts.PickVisualMedia(), uri -> {
            if (uri != null) {
                String imgPath = FileUtils.getFileAbsolutePath(getActivity(), uri);
                imageUpload(uri, imgPath);
                LogUtil.e("me", "imgPath->" + imgPath);
            }
        });
        loadData();
    }

    @NonNull
    private GridLayoutManager getGridLayoutManager() {
        GridLayoutManager layoutManager1 = new GridLayoutManager(getApplicationContext(), 4);
        layoutManager1.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return 2;
            }
        });
        layoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
        return layoutManager1;
    }


    void deleteImg(int position) {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < list2.size(); i++) {
            if (i != position) {
                list.add(list2.get(i));
            }
        }
        list2.clear();
        list2.addAll(list);
        typeAdapter.updateAllData();
    }

    void loadData() {
        if (getActivity() != null && !isFinishing()) {
            binding.tvInput.setSelected(false);
            binding.tvEmail.setSelected(false);
            list2.clear();
            list2.add("");
            typeAdapter.setIndex(-1);
            typeAdapter.updateAllData();
            imgAdapter.updateAllData();
            binding.tvInput.setText("");
            binding.tvEmail.setText("");
        }
    }

    void submit() {

        int type = typeAdapter.getIndex();
        if (type == -1) {
            Toast.makeText(this, getResources().getString(R.string.feedback_hit3), Toast.LENGTH_LONG).show();
            return;
        }
        String typestr = "";
        switch (type) {
            case 0:
                typestr = "SUGGEST";
                break;
            case 1:
                typestr = "BUG-APP";
                break;
            case 2:
                typestr = "PAYMENT";
                break;
            case 3:
                typestr = "OTHER";
                break;
        }

        String opinion = binding.tvInput.getText().toString();
        if (TextUtils.isEmpty(opinion)) {
            Toast.makeText(this, getResources().getString(R.string.feedback_hit5), Toast.LENGTH_LONG).show();
            return;
        }
        String emailStr = binding.tvEmail.getText().toString();
        if (TextUtils.isEmpty(emailStr)) {
            Toast.makeText(this, getResources().getString(R.string.feedback_hit4), Toast.LENGTH_LONG).show();
            return;
        }
        StringBuffer images = new StringBuffer();
        for (int i = 0; i < list2.size(); i++) {
            String url = list2.get(i);
            if (!TextUtils.isEmpty(url)) {
                if (TextUtils.isEmpty(images)) {
                    images.append(url);
                } else {
                    images.append(",").append(url);
                }
            }
        }


        showLoading("");
        String token = SpUtils.get_string(this, SpUtils.KEY_TOKEN, "");
        JsonObject json = BaseParams.getJsonObject(getActivity(), PathMaping.PathList[10], U.URL_MAIN_PRODUCT, token);
        json.addProperty("type", typestr);
        json.addProperty("opinion", opinion);
        json.addProperty("email", emailStr);


        if (score >= 0) {
            json.addProperty("starNum", score);
        }
        json.addProperty("images", images.toString());
        HashMap<String, String> heads = new HashMap<>();
        heads.put("product", U.URL_MAIN_PRODUCT);
        if (!TextUtils.isEmpty(U.URL_COUNTRY)) {
            heads.put("country", U.URL_COUNTRY);
        }
        String data = AESCryptUtilJar.encryptDefault(json.toString());
        LogUtil.e("me", json + "<-submit post->" + data);
        RxHttp.post(U.commonUrl, data, heads)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull String s) {
                        hideLoading();
                        if (!TextUtils.isEmpty(s)) {
                            String json1 = AESCryptUtilJar.decryptDefault(s);
                            LogUtil.e("me", "<-submit json->" + json1);
                            if (JsonParse.getCode(json1)) {
                                showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.feedback_hit6));
                                if (mHandler != null) {
                                    mHandler.sendEmptyMessageDelayed(TIME_WHAT, 1000);
                                }
                            } else {
                                showToastDialog(R.mipmap.hit_icon, JsonParse.getMsg(getActivity(), json1));
                            }
                        }
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                        hideLoading();
                        showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.start_net_failed));
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == TIME_WHAT) {
                if (getActivity() != null && !isFinishing() && !isDestroyed()) {
                    loadData();
                }
            }
        }
    };


    void showPhotoChooseDialog() {
        if (photoDialog == null) {
            photoDialog = new PhotoDialog(this);
        }
        photoDialog.setOnBtnClickListener(new BaseDialog.BtnClickListener() {
            @Override
            public void btnOnClickOk() {
                int type = photoDialog.getType();
                if (type == 1) {
                    toTakePhoto();
                } else if (type == 2) {
                    formAlbum();
                }
            }

            @Override
            public void btnOnClickCancel() {

            }

            @Override
            public void btnOnClickColse() {

            }
        });
        photoDialog.show();
    }

    final ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                LogUtil.e("me", "--onActivityResult--");
                if (result.getResultCode() == RESULT_OK) {
                    Intent data = result.getData();
                    if (data != null) {
                        String url = data.getStringExtra("url");
                        LogUtil.e("me", "onActivityResult url->" + url);
                        if (!TextUtils.isEmpty(url)) {
                            list2.add(url);
                            imgAdapter.updateAllData();
                        }
                    }
                }
            }
    );

    void toTakePhoto() {
        Intent intent = new Intent(this, SimbaCameraActivity.class);
        intent.putExtra("isHide", true);
        someActivityResultLauncher.launch(intent);
    }


    void formAlbum() {
        if (pickMedia != null) {
            pickMedia.launch(new PickVisualMediaRequest.Builder()
                    .setMediaType(ActivityResultContracts.PickVisualMedia.ImageOnly.INSTANCE)
                    .build());
        }
    }

    void imageUpload(Uri imageUri, String path) {
        showLoading(ResUtils.s(R.string.upload));
        LogUtil.e("me", "URL.uploadUrl->" + U.uploadUrl);
        RxHttp.uploadImage(U.uploadUrl, ImgUitls.compressToTargetSize(this, imageUri, 1024, path))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull String s) {
                        hideLoading();
                        if (!TextUtils.isEmpty(s)) {
                            String url = JsonParse.imageUploadJson2Obj(s);
                            LogUtil.e("me", "imageUpload url->" + url);
                            if (!TextUtils.isEmpty(url)) {
                                showToastDialog(R.mipmap.hit_icon2, ResUtils.s(R.string.upload_completed));
                                list2.add(url);
                                imgAdapter.updateAllData();
                            }
                        }
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                        if (e != null) {
                            LogUtil.e("me", "imageUpload e->" + e);
                        }
                        hideLoading();
                        showToastDialog(R.mipmap.hit_icon, ResUtils.s(R.string.upload_failed));
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (photoDialog != null) {
            photoDialog.dismiss();
        }
        if (mHandler != null) {
            mHandler.removeMessages(TIME_WHAT);
            mHandler = null;
        }
    }


}
